<?php

class device_helper
{
    public static function code_generate() {
        $args = func_get_args();
        $res = '';
        foreach ($args as $value) {
            if (0 === strpos($value, '::')) {
                list($call, $len) = explode('|', substr($value, 2));
                $res .= call_user_func(array('self', $call), intval($len));
            } else {
                list($val, $len) = explode('|', $value);
                $res .= sprintf("%0${len}d", $val);
            }
        }

        return $res;
    }

    public static function RAND($length = 10) {
        return mt_rand(pow(10, $length - 1), pow(10, $length) - 1);
    }

    /**
     * 获取设备类型
     *
     * @param $code
     * @return bool|string
     */
    public static function get_device_type_by_code($code) {
        if (!$code) {
            return false;
        }
        return strtoupper(substr($code, 0, 2));
    }

    /**
     * 通过设备码获取设备ID
     *
     * @param $code
     * @return bool
     */
    public static function get_device_id_by_code($code) {

        $type = self::get_device_type_by_code($code);

        // 设备前缀不符
        if (!array_key_exists($type, device_config::$TYPES)) {
            return false;
        }
        $device_info = _uri('device', array("code" => $code));
        if ($device_info) {
            return $device_info['id'];
        } else {
            return false;
        }
    }

    /**
     * 根据合伙人id和相关状态获取绑定设备总数
     *
     * @param $id
     * @return bool
     */
    public static function get_bind_device_count_by_agency_id($agency_id) {
        $filter = array();
        $filter['agency_id'] = $agency_id;
        $filter['status'] = 2;
        $count = _model('store_device_relation')->getTotal($filter);
        return $count;
    }

    /**
     * 根据合伙人id和相关状态获取绑定设备总数
     *
     * @param $id
     * @return bool
     */
    public static function get_bind_device_type_count_by_store_id($store_id, $type = '', $filter = array()) {
        if (!$store_id) {
            return 0;
        }
        $filter['store_id'] = $store_id;
        if (!isset($filter['status'])) {
            $filter['status'] = 2;
        }
        if ($type) {
            $filter['type'] = $type;
        }
        return _model('store_device_relation')->getTotal($filter);
    }


    /**
     * 通过总店id获取总店下所有的设备数量
     */
    public static function get_bind_device_count_by_owner_id($owner_id, $store_filter = array(), $device_filter = array()) {
        if (!$owner_id) {
            return 0;
        }

        if ($store_filter) {
            $store_list = store_helper::get_store_list_by_owner_id($owner_id, $store_filter);
        } else {
            $store_list = store_helper::get_store_list_by_owner_id($owner_id);
        }

        if (!$store_list) {
            return $owner_id;
        }
        $device_num = 0;
        foreach ($store_list as $k => $v) {
            $device_filter['store_id'] = $v['id'];
            $device_filter['status'] = 2;
            $device_num += _model('store_device_relation')->getTotal($device_filter);
        }

        return $device_num;
    }

    /**
     * 获取指定类型的设备码
     *
     * @param string $type
     * @param int $status
     * @return array
     * @throws AnException
     */
    public static function get_device_no_list_by_type($type = 'machine', $status = 2) {
        if (!in_array($type, device_config::$TYPES)) {
            return array();
        }
        return _model($type)->getList(array('status' => $status));
    }

    /**
     * 获取设备绑定关系
     *
     * @param $device_id
     * @return array
     */
    public static function get_store_device_relation($device_id) {
        return _uri('store_device_relation', array('dev_id' => $device_id));
    }

    /**
     * 判断店铺是否绑定设备
     *
     * @param $store_id
     * @return bool
     * @throws AnException
     */
    public static function is_bind_device($store_id) {
        if (!$store_id) {
            return false;
        }
        $res = _model('store_device_relation')->getList(array('store_id' => $store_id, 'status' => 2));
        if ($res) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取设备id
     *
     * @param {integer} $id
     * @return {bool|string}
     */
    public static function get_device_code_by_id($id) {
        $device_info = _uri('device', $id);
        if ($device_info) {
            return $device_info['code'];
        } else {
            return false;
        }
    }

    /**
     * 设备绑定
     *
     * @param $store_id
     * @param $device_no
     * @param $status
     * @param string $unbind_reason
     * @param string $extra
     * @return array
     * @throws AnException
     */
    public static function bind_store_device($store_id, $device_no, $status, $unbind_reason = '', $extra = '') {

        if (!$store_id || !$device_no) {
            return array('flag' => 'error', 'info' => '没有店铺id或设备号');
        }

        $type = self::get_device_type_by_code($device_no);
        $device_id = self::get_device_id_by_code($device_no);

        // 老设备 ZX
        if (!$device_id) {
            //必须为ZX1开头才可进行添加
            if ($type === 'ZX' && substr($device_no, 0, 3) === 'ZX1') {
                $device_id = _model('device')->create(array(
                    'code' => $device_no,
                    'type' => $type,
                    'status' => $status
                ));
            } else {
                return array('flag' => 'error', 'info' => '无法绑定, 请输入正确串码');
            }
        }

        // 再没有的话 报错吧, amen
        if (!$device_id) {
            return array('flag' => 'error', 'info' => '设备序列号不存在');
        }

        // 获得现有关系
        $device_relation_info = _uri('store_device_relation', array('dev_id' => $device_id, 'type' => $type));

        // 增加或更新绑定关系
        if ($device_relation_info) {
            if (isset($device_relation_info['status']) && 2 == $device_relation_info['status'] && 2 == $status) {
                return array('flag' => 'error', 'info' => '此设备已绑定');
            } elseif (1 == $device_relation_info['status'] && 1 == $status) {
                return array('flag' => 'error', 'info' => '此设备已解除绑定');
            }
            $RET = _model('store_device_relation')->update($device_relation_info['id'], array(
                'status' => $status,
                'store_id' => $store_id
            ));
        } else {
            $data = array(
                'store_id' => $store_id,
                'dev_id' => $device_id,
                'type' => $type,
                'res_id' => $device_id,
                'res_name' => device_config::$TYPES[$type]['id'],
                'status' => $status,
                'agency_id' => store_helper::get_agency_id_by_store_id($store_id),
                'add_time' => datetime()
            );
            $RET = _model('store_device_relation')->create($data);
        }

        if (1 == $status) { // 停用,解除绑定
            self::save_user_device_record($store_id, $type, $device_id, $status, $unbind_reason, $extra);
        } else { // 绑定
            self::save_user_device_record($store_id, $type, $device_id, $status);
        }

        // 更新设备状态
        self::update_device_status($device_no, $status);

        return $RET ? array('flag' => 'success', 'info' => 'success') : array('flag' => 'error', 'info' => '绑定失败');
    }

    /**
     * 更新设备状态
     *
     * @param $code
     * @param int $status
     * @return bool
     * @throws AnException
     */
    public static function update_device_status($code, $status = 2) {
        $type = self::get_device_type_by_code($code);

        // 设备前缀不符
        if (!array_key_exists($type, device_config::$TYPES)) {
            return false;
        }
        return _model('device')->update(array("code" => $code), array('status' => $status));
    }

    /**
     * 记录用户设备的操作
     *
     * @param $store_id
     * @param $type
     * @param $dev_id
     * @param $status
     * @param string $unbind_reason
     * @param string $extra
     * @return mixed
     * @throws AnException
     */
    public static function save_user_device_record($store_id, $type, $dev_id, $status, $unbind_reason = '', $extra = '') {
        $data['store_id'] = $store_id;
        $data['type'] = $type;
        $data['dev_id'] = $dev_id;
        $data['status'] = $status;
        $data['add_time'] = datetime();
        $data['unbind_reason'] = $unbind_reason;
        $data['extra'] = substr($extra, 0, 200);

        return _model('store_device_record')->create($data);
    }

    /**
     * 获取设备绑定信息概览
     */
    public static function get_store_device_list_by_store_id($store_id, $filter = array()) {
        if (!$store_id) {
            return array();
        }

        //$res_map = api_helper::array_to_filelds_assoc('id', device_config::$TYPES);
        $filter['store_id'] = $store_id;
        $filter['status'] = 2;

        $list = array();
        foreach (device_config::$TYPES as $item) {
            if (!$item['bindable']) {
                continue;
            }
            $type = $item['prefix'];
            $filter['type'] = $type;
            // 统计每种类型的设备数量
            $device_num = _model('store_device_relation')->getTotal($filter);

            array_push($list, array(
                'res_name' => $item['id'],
                'device_num' => $device_num,
                'device_num_str' => '已绑定设备：' . $device_num . '台',
                'allow_bind' => $item['bindable'],
            ));
        }

        return $list;
    }

    /**
     * 获取门店所有类型的设备绑定的列表
     */
    public static function get_store_all_device_list_by_store_id($store_id) {
        if (!$store_id) {
            return array();
        }

        $filter = array();
        $filter['store_id'] = $store_id;
        $filter['status'] = 2;
        $device_relation_list = _model('store_device_relation')->getList($filter);
        if (!$device_relation_list) {
            return array();
        }

        $all_device_list = array();
        foreach ($device_relation_list as $item) {
            if (!isset($all_device_list[$item['type']])) {
                $all_device_list[$item['type']] = array();
            }
            $all_device_list[$item['type']][] = array(
                'id' => $item['dev_id'],
                'device_no' => self::get_device_code_by_id($item['dev_id']),
                'type' => $item['type'],
                'res_name' => device_config::$TYPES[$item['type']]['id'],
                'res_name_str' => device_config::$TYPES[$item['type']]['name'],
                'name' => device_config::$TYPES[$item['type']]['name'],
            );
        }

        $device_list = array();
        foreach ($all_device_list as $item) {
            if (!empty($item)) {
                array_push($device_list, $item);
            }
        }

        return $device_list;
    }

    /**
     * 获取门店某一分类的设备
     *
     * @param $store_id
     * @param $type
     * @return array
     * @throws AnException
     */
    public static function get_store_typed_device_by_store_id($store_id, $res_name) {
        if (!$store_id) {
            return array();
        }

        $RES = device_config::res_index();
        $type = $RES[$res_name]['prefix'];

        if (!array_key_exists($type, device_config::$TYPES)) {
            return array();
        }
        $filter = array();
        $filter['type'] = $type;
        $filter['store_id'] = $store_id;
        $filter['status'] = 2;
        $device_relation_list = _model('store_device_relation')->getList($filter);
        if (!$device_relation_list) {
            return array();
        }

        $device_list = array();
        foreach ($device_relation_list as $k => $v) {
            $device_info = _uri('device', $v['dev_id']);
            if ($device_info) {
                $info['id'] = $device_info['id'];
                $info['device_no'] = $device_info['code'];

                array_push($device_list, $info);
            }
        }

        return $device_list;
    }
}